import Vue from 'vue'
import Vuex from 'vuex'
import persisted from "vuex-persistedstate";
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 全局的状态
    userInfo: null,
    shopCarList: [],
    preImgShow: false,
    imgURLList: [],
    actionSheetConfig: {
      isShow: false,
      list: [],
      successCallBack: null
    }
  },
  mutations: {
    // 改变状态state
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    addShopCarList(state, foodsInfo) {
      let index = state.shopCarList.findIndex(item => item.fid == foodsInfo.fid);
      if (index == -1) {
        state.shopCarList.push(foodsInfo);
      } else {
        state.shopCarList[index].count++;
      }
    },
    preImgShowOrHide(state, imgURLList) {
      state.preImgShow = !state.preImgShow;
      state.imgURLList = imgURLList;
    },
    logOut(state) {
      state.userInfo = null;
    },
    delFoods(state, fid) {
      let index = state.shopCarList.findIndex(item => item.fid == fid);
      if (index != -1) {
        state.shopCarList.splice(index, 1);
      }
    },
    cleanShopCar(state) {
      state.shopCarList.splice(0);
    },
    showActionSheet(state,config) {
      state.actionSheetConfig.isShow = true;
      state.actionSheetConfig.list = config.list;
      state.actionSheetConfig.successCallBack = config.success;
    },
    // 关闭actionSheet
    hideActionSheet(state) {
      state.actionSheetConfig.isShow = false;
      state.actionSheetConfig.list = [];
    },
  },
  actions: {
    // 将数据提交给mutations
    setUserInfo({
      commit
    }, userInfo) {
      // 将数据通过commit传递给mutations中的setUserInfo
      commit("setUserInfo", userInfo);
    },
    addShopCarList({
      commit
    }, foodsInfo) {
      commit("addShopCarList", foodsInfo);
    },
    preImgShowOrHide({
      commit
    }, imgURLList) {
      commit("preImgShowOrHide", imgURLList);
    },
    logOut({
      commit
    }) {
      commit("logOut");
    },
    delFoods({
      commit
    }, fid) {
      commit("delFoods", fid);
    },
    cleanShopCar({
      commit
    }) {
      commit("cleanShopCar");
    },
    showActionSheet({
      commit
    }, config) {
      commit("showActionSheet", config);
    },
    hideActionSheet({
      commit
    }) {
      commit("hideActionSheet");
    }
  },
  plugins: [
    // 将缓存的数据放到session中
    persisted({
      storage: sessionStorage
    })
  ],
  // 相当于计算属性
  getters: {
    // 这里的state值得就是前面的state
    getCount(state) {
      if (state.userInfo) {
        let sum = 0;
        state.shopCarList.forEach(item => {
          sum += item.count;
        });
        return sum;
      } else {
        return 0;
      }
    },
    getMoney(state) {
      if (state.userInfo) {
        let sum = 0;
        state.shopCarList.forEach(item => {
          sum += item.count * item.price;
        });
        return sum;
      } else {
        return 0;
      }
    }
  },
  modules: {}
});